/**
 * 日志拦截器
 * @author yanwl 
 * @date 2015-01-29
 */
package com.chnbst.bstyun.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.chnbst.bstyun.eos.IPUtil;
import com.chnbst.bstyun.model.pojo.AdminUser;
import com.chnbst.bstyun.model.pojo.Operate;
import com.chnbst.bstyun.model.pojo.OperateLog;
import com.chnbst.bstyun.service.AdminUserService;
import com.chnbst.bstyun.service.OperateLogService;
import com.chnbst.bstyun.service.OperateService;

/**
 * 日志记录AOP
 * 
 * @author yanwl
 * @date 2015-01-29
 */
public class LogInterceptor implements HandlerInterceptor {
	@Autowired
	private OperateService operateService;
	@Autowired
	private OperateLogService operateLogService;
	@Autowired
	private AdminUserService adminUserService;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		String contextPath = request.getContextPath();
		String url = request.getRequestURI();
		if (contextPath.length() > 1) {
			url = url.substring(contextPath.length());
		}
		
		AdminUser admin = (AdminUser) request.getSession().getAttribute("adminUser");
		//获取Ip
		String ip = IPUtil.getIpAddr(request);
		Operate operate = operateService.selectByOperateUrl(url);
		if(operate != null) {
			if(admin == null) {
				if("/loginAdmin/userQuit".equals(url)) {
					String adminId = (String)request.getSession().getAttribute("adminId");
					admin = adminUserService.selectById(Integer.valueOf(adminId));
				}else {
					return;
				}
			}
			
			//新增操作日志
			OperateLog log = new OperateLog();
			log.setLoginIp(ip);
			log.setOperateContent(operate.getOperateContent());
			log.setOperateName(admin.getAdminName());
			log.setOperateTime(new Date());
			operateLogService.insertOperateLog(log);
		}else {
			return;
		}

	}
}
